package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

type Post struct {
	Id            int
	Post_title    string
	Post_img      string
	Post_tags     string
	Post_desc     string
	Post_type     string
	Post_text     string
	Post_author   string
	Post_urlname  string
	Post_datetime string
	Post_category string
}

func (p *Post) TableName() string {
	return "mt_system_post"
}

func init() {
	orm.RegisterModel(new(Post))
}

func AddPost(post Post) (int64, error) {

	o := orm.NewOrm()
	o.Using("default")

	var _post Post
	_post = post
	id, err := o.Insert(&_post)
	if err == nil {
		fmt.Println(id)
	}

	return id, err
}

func UpdatePost(post Post) (int64, error) {

	o := orm.NewOrm()
	o.Using("default")

	var _post Post
	_post = post
	id, err := o.Update(&_post)
	if err == nil {
		fmt.Println(id)
	}

	return id, err
}

func DelPostById(id int) (int64, error) {

	var post Post

	o := orm.NewOrm()
	o.Using("default")

	if 0 != id {
		post.Id = id
	}
	return o.Delete(&post)
}

func DelPostByName(urlname string) (int64, error) {

	var post Post

	o := orm.NewOrm()
	o.Using("default")

	if "" != urlname {
		post = Post{Post_urlname: urlname}
		o.Read(&post, "Post_urlname")
	}
	return o.Delete(&post)
}

func GetPostById(id int) (Post, error) {

	var err error
	var post Post

	o := orm.NewOrm()
	o.Using("default")
	post = Post{Id: id}
	err = o.Read(&post, "Id")
	return post, err
}

func GetPostByName(urlname string) (Post, error) {

	var err error
	var post Post

	o := orm.NewOrm()
	o.Using("default")
	post = Post{Post_urlname: urlname}
	err = o.Read(&post, "Post_urlname")
	return post, err
}

func GetPosts() ([]orm.Params, error) {
	var (
		maps []orm.Params
	)

	sql1 := "select * from mt_system_post"
	o := orm.NewOrm()

	num, err := o.Raw(sql1).Values(&maps)

	if err == nil && num > 0 {
		fmt.Println(num)
		return maps, nil
	} else {
		return nil, err
	}
}
